<template>
  <div v-if="error" class="error-boundary">
    <div class="error-content">
      <el-result
        icon="error"
        title="页面出现错误"
        :sub-title="error.message || '未知错误'"
      >
        <template #extra>
          <el-button type="primary" @click="handleRetry">重试</el-button>
          <el-button @click="handleGoHome">返回首页</el-button>
        </template>
      </el-result>
    </div>
  </div>
  <slot v-else></slot>
</template>

<script setup lang="ts">
import { ref, onErrorCaptured } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()
const error = ref<Error | null>(null)

onErrorCaptured((err: Error) => {
  error.value = err
  console.error('ErrorBoundary caught an error:', err)
  return false // 阻止错误继续传播
})

const handleRetry = () => {
  error.value = null
  window.location.reload()
}

const handleGoHome = () => {
  error.value = null
  router.push('/')
}
</script>

<style scoped lang="scss">
.error-boundary {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 400px;
  
  .error-content {
    text-align: center;
  }
}
</style> 